package com.web.exiaodao.business.service.impl;

import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.web.webstart.base.service.impl.BaseService;
import com.web.webstart.base.exception.BusinessException;
import com.web.webstart.base.constant.XaConstant;
import com.web.webstart.base.util.jpa.DynamicSpecifications;
import com.web.webstart.base.util.jpa.MyPage;
import com.web.webstart.base.util.jpa.SearchFilter;
import com.web.webstart.base.util.jpa.SearchFilter.Operator;
import com.web.webstart.base.util.result.XaResult;
import com.web.webstart.base.util.XaUtil;
import com.web.exiaodao.business.constant.JConstant;
import com.web.exiaodao.business.entity.Banner;
import com.web.exiaodao.business.repository.BannerRepository;
import com.web.exiaodao.business.service.BannerService;

@Service("BannerService")
@Transactional(readOnly = false)
public class BannerServiceImpl extends BaseService<Banner> implements BannerService {

	private static final Logger LOGGER = Logger.getLogger(BannerServiceImpl.class);

	@Autowired
	private BannerRepository bannerRepository;
	
	/**
	 * 查询单条Banner信息
	 * //@param tId
	 * @return 返回单个Banner对象
	 * @throws BusinessException
	 */
	@Transactional(readOnly = true, rollbackFor = Exception.class)
	public XaResult<Banner> findOne(Long modelId) throws BusinessException {
		Banner obj = new Banner();
		if(modelId != 0){
			obj = bannerRepository.findByIdAndStatusNot(modelId,XaConstant.Status.delete);
		}
		XaResult<Banner> xr = new XaResult<Banner>();
		if (XaUtil.isNotEmpty(obj)) {
			xr.setObject(obj);
			LOGGER.info("后台----->查询单个实体----->Banner");
		} else {
			xr.error(XaConstant.Message.object_not_find);
			LOGGER.info(XaConstant.Message.object_not_find);
		}
		return xr;
	}

	/**
	 * 分页查询状态非status的Banner数据
	 * @param status
	 * @param filterParams
	 * @param pageable
	 * @return 返回对象Banner集合
	 * @throws BusinessException
	 */
	@Transactional(readOnly = true, rollbackFor = Exception.class)
	public XaResult<Page<Banner>> findListNEStatusByFilter(
			Integer status, Map<String, Object> filterParams, Pageable pageable) throws BusinessException {
		Map<String, SearchFilter> filters = SearchFilter.parse(filterParams);
		if(status == null){// 默认显示非删除的所有数据
			status = XaConstant.Status.delete;
		}
		filters.put("status", new SearchFilter("status", Operator.NE, status));
		Page<Banner> page = bannerRepository.findAll(DynamicSpecifications
				.bySearchFilter(filters.values(), Banner.class), pageable);
		XaResult<Page<Banner>> xr = new XaResult<Page<Banner>>();
		xr.setObject(page);
		LOGGER.info("后台----->分页查询实体集合（状态不等于）----->Banner");
		return xr;
	}

	/**
	 * 分页查询状态status的Banner数据
	 * @param status
	 * @param filterParams
	 * @param pageable
	 * @return 返回对象Banner集合
	 * @throws BusinessException
	 */
	@Transactional(readOnly = true, rollbackFor = Exception.class)
	public XaResult<Page<Banner>> findListEQStatusByFilter(
			Integer status, Map<String, Object> filterParams, Pageable pageable) throws BusinessException {
		Map<String, SearchFilter> filters = SearchFilter.parse(filterParams);
		if(status == null){// 默认显示正常数据
			status = XaConstant.Status.valid;
		}
		filters.put("status", new SearchFilter("status", Operator.EQ, status));
//		List<Banner> banner = bannerRepository.findByTypeAndStatusNot(JConstant.BannerType.HOME_BANNER, XaConstant.Status.delete);
		List<Banner> banner = bannerRepository.findList();
		int count=banner.size();
		Page<Banner> page= new MyPage<Banner>(pageable.getPageNumber(),pageable.getPageSize(),banner,count);
		XaResult<Page<Banner>> xr = new XaResult<Page<Banner>>();
		xr.setObject(page);
		LOGGER.info("后台----->分页查询实体集合（状态等于）----->Banner");
		return xr;
	}

	/**
	 * 保存Banner信息
	 * @param model
	 * @return
	 * @throws BusinessException
	 */
	@Transactional(rollbackFor = Exception.class)
	public XaResult<Banner> saveOrUpdate(Banner model) throws BusinessException {
		XaResult<Banner> xr = new XaResult<Banner>();
		Banner obj = null;
		if(XaUtil.isNotEmpty(model.getId())){
			obj = bannerRepository.findOne(model.getId());
		}else{
			obj = new Banner();
		}
		Banner banner = bannerRepository.findByTypeAndSortAndStatusNot(model.getType(), model.getSort(), XaConstant.Status.delete);
	    if(XaUtil.isNotEmpty(banner)){
	    	xr.error("排序值不能重复");
	    }
		obj.setPicurl(XaUtil.isNotEmpty(model.getPicurl()) ? model.getPicurl() : obj.getPicurl());
	    obj.setLinkurl(XaUtil.isNotEmpty(model.getLinkurl()) ? model.getLinkurl() : obj.getLinkurl());
	    obj.setType(XaUtil.isNotEmpty(model.getType()) ? model.getType() : obj.getType());
	    obj.setSort(XaUtil.isNotEmpty(model.getSort()) ? model.getSort() : obj.getSort());
	    obj.setIntro(XaUtil.isNotEmpty(model.getIntro()) ? model.getIntro() : obj.getIntro());
	    obj.setObjectId(XaUtil.isNotEmpty(model.getObjectId()) ? model.getObjectId() : obj.getObjectId());
		obj = bannerRepository.save(obj);
		xr.setObject(obj);
		LOGGER.info("后台新增或编辑数据成功！");
		return xr;
	}

	/**
	 * 修改Banner状态，可一次修改多条   3删除  -1锁定  1正常
	 * //@param userId
	 * @param modelIds
	 * @param status
	 * @return 返回Banner对象
	 * @throws BusinessException
	 */
	@Transactional(rollbackFor = Exception.class)
	public XaResult<Banner> multiOperate(
			String modelIds,Integer status) throws BusinessException {
		XaResult<Banner> xr = new XaResult<Banner>();
		if(status == null){
			status = XaConstant.Status.delete;
		}
		if(modelIds != null){
			String[] ids = modelIds.split(",");
			for(String id : ids){
				Banner obj = bannerRepository.findByIdAndStatusNot(Long.parseLong(id),status);
				if (XaUtil.isNotEmpty(obj)) {
					obj.setStatus(status);
					obj = bannerRepository.save(obj);
				}
			}
		}
		LOGGER.info("批量修改数据状态成功！");
		return xr;
	}

	@Override
	public XaResult<Page<Banner>> findListEQStatus(Integer status,
			Map<String,Object> filterParams, Pageable pageable) throws BusinessException {
		Map<String, SearchFilter> filters = SearchFilter.parse(filterParams);
		if(status == null){// 默认显示正常数据
			status = XaConstant.Status.valid;
		}
		filters.put("status", new SearchFilter("status", Operator.EQ, status));
		List<Banner> banner = bannerRepository.findList();
		if(XaUtil.isNotEmpty(filters.values())){
			if("1".equals(filterParams.get("EQ_type"))){   
				banner = bannerRepository.findListByTypeAndStatusNot(JConstant.BannerType.HOME_BANNER, XaConstant.Status.delete);
			}else if("5".equals(filterParams.get("EQ_type"))){
				banner = bannerRepository.findListByTypeAndStatusNot(JConstant.BannerType.TRAVEL_BANNER, XaConstant.Status.delete);
			}else if("6".equals(filterParams.get("EQ_type"))){
				banner = bannerRepository.findListByTypeAndStatusNot(JConstant.BannerType.GOODS, XaConstant.Status.delete);
			}
		}
		int count=banner.size();
		Page<Banner> page= new MyPage<Banner>(pageable.getPageNumber(),pageable.getPageSize(),banner,count);
		XaResult<Page<Banner>> xr = new XaResult<Page<Banner>>();
		xr.setObject(page);
		LOGGER.info("后台----->分页查询实体集合（状态等于）----->Banner");
		return xr;
	}
	
}
